﻿// ReSharper disable CheckNamespace => extensions should be available in the original namespace
namespace System.Collections.Generic
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Contains extension methods for dictionary types.
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// Saves the specified data to a dictionary.
        /// </summary>
        /// <typeparam name="T">The type of the data to save.</typeparam>
        /// <param name="dictionary">The dictionary to save the data to.</param>
        /// <param name="key">The key to use to save and retrieve the data.</param>
        /// <param name="data">The data to save.</param>
        public static void Save<T>(this IDictionary<string, object> dictionary, string key, T data)
        {
            if (dictionary == null)
            {
                return;
            }

            dictionary[key] = data;
        }

        /// <summary>
        /// Retrieves data from a dictionary using the specified key, casting back to the given type.
        /// </summary>
        /// <typeparam name="T">The type to cast the data back to.</typeparam>
        /// <param name="dictionary">The dictionary to use for data retrieval.</param>
        /// <param name="key">The key to use to look up the data.</param>
        /// <returns>The value, cast to the given type, or the default value for the specified type if the key was not found.</returns>
        public static T Retrieve<T>(this IDictionary<string, object> dictionary, string key)
        {
            return Retrieve(dictionary, key, default(T));
        }

        /// <summary>
        /// Retrieves data from a dictionary using the specified key, casting back to the given type.
        /// </summary>
        /// <typeparam name="T">The type to cast the data back to.</typeparam>
        /// <param name="dictionary">The dictionary to use for data retrieval.</param>
        /// <param name="key">The key to use to look up the data.</param>
        /// <param name="defaultValue">The value to return if the given key is not present in the dictionary.</param>
        /// <returns>The value, cast to the given type, or the given default value if the key was not found.</returns>
        public static T Retrieve<T>(this IDictionary<string, object> dictionary, string key, T defaultValue)
        {
            if (dictionary != null && dictionary.ContainsKey(key))
            {
                var result = (T)dictionary[key];
                return result;
            }

            return defaultValue;
        }
    }
}